import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


export default new Vuex.Store({
  state: {
    count: 0,
    cart: []
  },
  mutations: {
    // 添加到购物车
    addToCart(state, payload) {
      let flag = 0;
      state.cart.forEach(item => {
        if (item.name === payload.name) {
          item.count++;
          state.count++;
          flag = 1;
          return 0;
        }
      })
      if (!flag) {
        payload.count++;
        state.cart.push(payload);
        state.count++;
        console.log(state.cart);
        console.log(state.count);
      }

    },
    // 减掉购物车的菜
    decreaseFromCart(state, payload) {
      state.cart.forEach(item => {
        if (item.name === payload.name) {
          item.count--;
          state.count--;
        }
      })
      //删除数量为零的商品
      state.cart = state.cart.filter((item) => item.count > 0)
      //console.log(state.cart)
    },
    // 清空购物车
    clearCart(state) {
      state.cart = [];
      state.count = 0;
    },
  },
  actions: {
    // 异步操作，防止数据失效
    // 将异步操作封装为一个Promise对象
    aAddToCart(context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit('addToCart', payload);
          resolve();
        }, 1)
      })
    },
    adecreaseFromCart(context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit('decreaseFromCart', payload);
          resolve();
        }, 1)
      })
    },
    aClearCart(context) {
      return new Promise((resolve) => {
        setTimeout(() => {
          context.commit('clearCart');
          resolve();
        }, 1)
      })
    },
  },
  modules: {
  }
})